// 游戏列表页面的交互逻辑

document.addEventListener('DOMContentLoaded', () => {
    // 初始化变量
    const filtersForm = document.querySelector('.filters-container');
    const gamesGrid = document.querySelector('.games-grid');
    const sortSelect = document.querySelector('.games-sort select');
    const searchInput = document.querySelector('.search-container input');
    const gamesCount = document.querySelector('.games-count span');
    const pagination = document.querySelector('.pagination');

    // 游戏数据（示例）
    let games = [
        {
            id: 1,
            title: '贪吃蛇',
            image: 'https://via.placeholder.com/300x400',
            categories: ['休闲', '益智'],
            rating: 4.8,
            badge: '经典',
            url: 'game.html'
        },
        {
            id: 2,
            title: '俄罗斯方块',
            image: 'https://via.placeholder.com/300x400',
            categories: ['休闲', '益智'],
            rating: 4.9,
            badge: '经典',
            url: '#'
        },
        // 可以添加更多游戏数据
    ];

    // 当前筛选和排序状态
    let currentFilters = {
        categories: [],
        rating: [],
        status: []
    };
    let currentSort = 'popular';
    let currentSearch = '';
    let currentPage = 1;
    const gamesPerPage = 12;

    // 更新游戏列表显示
    function updateGamesList() {
        // 应用筛选
        let filteredGames = games.filter(game => {
            // 分类筛选
            if (currentFilters.categories.length > 0) {
                if (!game.categories.some(cat => currentFilters.categories.includes(cat))) {
                    return false;
                }
            }
            // 评分筛选
            if (currentFilters.rating.length > 0) {
                if (!currentFilters.rating.some(rating => game.rating >= parseFloat(rating))) {
                    return false;
                }
            }
            // 搜索筛选
            if (currentSearch) {
                if (!game.title.toLowerCase().includes(currentSearch.toLowerCase())) {
                    return false;
                }
            }
            return true;
        });

        // 应用排序
        filteredGames.sort((a, b) => {
            switch (currentSort) {
                case 'rating':
                    return b.rating - a.rating;
                case 'newest':
                    return b.id - a.id; // 假设 id 越大表示越新
                default: // popular
                    return b.rating * 1000 + b.id - (a.rating * 1000 + a.id);
            }
        });

        // 更新总数显示
        gamesCount.textContent = filteredGames.length;

        // 分页处理
        const totalPages = Math.ceil(filteredGames.length / gamesPerPage);
        const start = (currentPage - 1) * gamesPerPage;
        const end = start + gamesPerPage;
        const paginatedGames = filteredGames.slice(start, end);

        // 渲染游戏卡片
        gamesGrid.innerHTML = paginatedGames.map(game => `
            <div class="game-card">
                <div class="game-image">
                    <img src="${game.image}" alt="${game.title}">
                    <div class="game-overlay">
                        <a href="${game.url}" class="play-now">立即开玩</a>
                    </div>
                    ${game.badge ? `<span class="game-badge">${game.badge}</span>` : ''}
                </div>
                <div class="game-info">
                    <h3>${game.title}</h3>
                    <div class="game-meta">
                        <div class="game-tags">
                            ${game.categories.map(cat => `<span>${cat}</span>`).join('')}
                        </div>
                        <div class="game-rating">
                            <span class="star">★</span>
                            <span class="rating">${game.rating}</span>
                        </div>
                    </div>
                </div>
            </div>
        `).join('');

        // 更新分页控件
        updatePagination(totalPages);
    }

    // 更新分页控件
    function updatePagination(totalPages) {
        const pageNumbers = document.querySelector('.page-numbers');
        const prevBtn = document.querySelector('.page-btn.prev');
        const nextBtn = document.querySelector('.page-btn.next');

        // 更新前后按钮状态
        prevBtn.disabled = currentPage === 1;
        nextBtn.disabled = currentPage === totalPages;

        // 生成页码按钮
        let pages = [];
        if (totalPages <= 5) {
            for (let i = 1; i <= totalPages; i++) {
                pages.push(i);
            }
        } else {
            if (currentPage <= 3) {
                pages = [1, 2, 3, 4, '...', totalPages];
            } else if (currentPage >= totalPages - 2) {
                pages = [1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
            } else {
                pages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
            }
        }

        pageNumbers.innerHTML = pages.map(page => {
            if (page === '...') {
                return '<span class="page-ellipsis">...</span>';
            }
            return `
                <button class="page-number ${page === currentPage ? 'active' : ''}">${page}</button>
            `;
        }).join('');
    }

    // 事件监听器
    filtersForm.addEventListener('change', e => {
        if (e.target.matches('input[type="checkbox"]')) {
            const filterType = e.target.name;
            const value = e.target.value;
            
            if (e.target.checked) {
                currentFilters[filterType].push(value);
            } else {
                currentFilters[filterType] = currentFilters[filterType].filter(v => v !== value);
            }
            
            currentPage = 1;
            updateGamesList();
        }
    });

    sortSelect.addEventListener('change', e => {
        currentSort = e.target.value;
        currentPage = 1;
        updateGamesList();
    });

    let searchTimeout;
    searchInput.addEventListener('input', e => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentSearch = e.target.value;
            currentPage = 1;
            updateGamesList();
        }, 300);
    });

    pagination.addEventListener('click', e => {
        if (e.target.matches('.page-number')) {
            currentPage = parseInt(e.target.textContent);
            updateGamesList();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        } else if (e.target.matches('.page-btn.prev:not(:disabled)')) {
            currentPage--;
            updateGamesList();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        } else if (e.target.matches('.page-btn.next:not(:disabled)')) {
            currentPage++;
            updateGamesList();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        }
    });

    // 初始化显示
    updateGamesList();
});
